﻿using Furion.CMS.Application.Dto;
using Furion.DatabaseAccessor;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using Mapster;
using Microsoft.AspNetCore.Authorization;
using System.ComponentModel;
using Furion.CMS.Domain;

namespace Furion.CMS.Application
{
    /// <summary>
    /// 黑白名单应用服务
    /// </summary>
    [DisplayName("SafeManager")]
    public class BlackWhiteListAppService : BaseApplication
    {
        private readonly IRepository<Blacklist> _blacklistRepository;
        private readonly IRepository<Whitelist> _whitelistRepository;

        public BlackWhiteListAppService(IRepository<Blacklist> blacklistRepository, IRepository<Whitelist> whitelistRepository)
        {
            _blacklistRepository = blacklistRepository;
            _whitelistRepository = whitelistRepository;
        }

        /// <summary>
        /// 添加到黑名单中
        /// </summary>
        /// <param name="list"></param>
        [HttpPost]
        [SecurityDefine]
        public void AddBlacklist([FromBody] BlacklistInputDto[] list)
        {
            var ips = list.Select(s => s.IpAddress).Distinct().ToList();
            var updates = _blacklistRepository.Where(x => ips.Contains(x.HostAddress)).ToList();
            var existsIps = updates.Select(s => s.HostAddress);
            var addIps = ips.Except(existsIps).Distinct();
            if (updates.Any())
            {// 更新数据
                updates.ForEach(up =>
                {
                    var nItem = list.FirstOrDefault(x => x.IpAddress == up.HostAddress);
                    up.Description += $";{nItem.Description}";
                    up.UpdatedTime = DateTimeOffset.UtcNow;
                });
            }

            var addEntityList = list.Where(x => addIps.Contains(x.IpAddress)).Adapt<Blacklist[]>();
            if (addEntityList.Any())
            {
                _blacklistRepository.Insert(addEntityList);
            }

            _blacklistRepository.SaveNow();
        }

        /// <summary>
        /// 移除黑名单
        /// </summary>
        /// <param name="list"></param>
        [HttpDelete]
        [SecurityDefine]
        public void RemoveBlacklist([FromBody] string[] list)
        {
            var deletes = _blacklistRepository.AsQueryable(false)
                .Where(t => list.Contains(t.HostAddress))
                .ToList();

            _blacklistRepository.DeleteNow(deletes);
        }
    }
}
